//
//  MBHomeViewController.m
//  Meboo
//
//  Created by kyo on 2023/12/6.
//

#import "MBHomeViewController.h"
#import "NSHomeCell.h"
#import "MBRecruitmentViewController.h"
#import "MBChatListViewController.h"
#import "MBHomeListHeaderView.h"
#import "GKPhotoBrowser.h"
//pop
#import "MBHomeFirstPopView.h"
#import "MBHomePPVPopView.h"
@interface MBHomeViewController ()
<
UICollectionViewDelegate,
UICollectionViewDataSource
>
@property (nonatomic, strong) UIImageView *backImageView;
@property (nonatomic , strong) UICollectionView *imageCollectionView;
@property (nonatomic , strong) UICollectionView *videoCollectionView;
@property (nonatomic , strong) MBHomeListHeaderView *headerView;

@property (nonatomic, strong) NSMutableArray *imageArr;
@property (nonatomic, strong) NSMutableArray *videoArr;
@property (nonatomic, strong) NSMutableArray *videoAvatarArr;
@property (nonatomic, strong) NSMutableArray *videoTimeArr;
@property(nonatomic,strong) UILabel *titleLab;
@property (nonatomic , strong) UIButton *recruitmentBtn;


@property (nonatomic, strong) UIButton *messageBtn;
@property (nonatomic, assign) BOOL isConnect;
@property (nonatomic, assign) CGFloat beforeY;
@property (nonatomic , strong) NSMutableArray *dataArr;

//pop
@property (nonatomic , strong) MBHomeFirstPopView *homeFirstPopView;
@property (nonatomic , strong) MBHomePPVPopView *homePPVPopView;
@end

@implementation MBHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //程序入口的标识符赋值, 决定着后续子业务的区别
    MBUserAccount *account = [MBUserAccount defaultAccount];
    account.isNewHome = 1;
    [MBUserAccount saveAccount:account];
    
    self.view.backgroundColor = HEXS(@"ffffff");
    self.navigationController.navigationBarHidden = YES;
    [self setupUI];
    [self getRongCloudToken];
}

#pragma mark - Private Method

- (void)getRongCloudToken {
    __WeakSelf
    [[MBChatDataManager sharedManager] getRongCloudToken:^(BOOL success) {
        if (success) {
            [weakSelf getRongCloudConnectState];
        }
    }];
}

- (void)getRongCloudConnectState {
    __WeakSelf
    [[RCIM sharedRCIM] connectWithToken:[MBUserAccount defaultAccount].rongCloudToken
                               dbOpened:^(RCDBErrorCode code) {
        //消息数据库打开，可以进入到主页面
    } success:^(NSString *userId) {
        //连接成功,可跳转至会话列表页
        //存储本人的userid
        MBUserAccount  *account = [MBUserAccount defaultAccount];
        account.chatUserId = userId;
        [MBUserAccount  saveAccount:account];
        weakSelf.isConnect = YES;
    }error:^(RCConnectErrorCode status) {
        weakSelf.isConnect = NO;
        if (status == RC_CONN_TOKEN_INCORRECT) {
            //从 APP 服务获取新 token，并重连
            NSLog(@"");
        } else {
            //无法连接到 IM 服务器，请根据相应的错误码作出对应处理
            NSLog(@"");
        }
    }];
}

- (void)getPayInfo {
    [[MBMineDataManager sharedManager] getMemberProductWithType:2 success:^(BOOL success) {
        
    }];
}

#pragma mark - Action
- (void)recruitmentAction {
    [self.navigationController pushViewController:[MBRecruitmentViewController new] animated:YES];
}

- (void)messageAction {
    NSArray *displayConversationTypeArray = @[@(ConversationType_PRIVATE)];
    MBChatListViewController *conversationListVC = [[MBChatListViewController alloc] initWithDisplayConversationTypes:displayConversationTypeArray
                                                                                           collectionConversationType:nil];
    [conversationListVC setConversationAvatarStyle:RC_USER_AVATAR_CYCLE];
    [self.navigationController pushViewController:conversationListVC animated:YES];
}

#pragma mark -- collectionView  delegate datasource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (collectionView == self.imageCollectionView) {
        return self.imageArr.count;
    } else {
        return self.videoAvatarArr.count;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
        NSHomeCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"NSHomeCell" forIndexPath:indexPath];
        if (indexPath.row < 5) {
            cell.isNew = YES;
        } else {
            cell.isNew = NO;
        }
    
    if (collectionView == self.imageCollectionView) {
        cell.isVideo = NO;
        cell.imageUrl = self.imageArr[indexPath.row];
        cell.isLocked = ![[MBUserAccount defaultAccount].ppBuyArr containsObject:[NSString stringWithFormat:@"%ld",indexPath.row]];
    } else {
        cell.isVideo = YES;
        cell.imageUrl = self.videoAvatarArr[indexPath.row];
        cell.timeLab.text = [NSString stringWithFormat:@"00:%@",self.videoTimeArr[indexPath.row]];
        cell.isLocked = ![[MBUserAccount defaultAccount].pvBuyArr containsObject:[NSString stringWithFormat:@"%ld",indexPath.row]];
    }
    
    if (indexPath.row < 2) {
        cell.isLocked = NO;
    }
        return cell;
}

//设置每个section的UIEdgeInsets
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(MBHeightScale(0), MBWidthScale(0), MBHeightScale(10), MBWidthScale(0));
}

//设置列间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return MBHeightScale(10);
}

//设置每个item水平间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return MBWidthScale(10);
}

//定义每一个cell的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake((ScreenWidth-MBWidthScale(48))/2, (ScreenWidth-MBWidthScale(48))/2 *218/164);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    MBUserAccount *account = [MBUserAccount defaultAccount];
    if (account.ppBuyArr.count == 0) {
        account.ppBuyArr = [NSMutableArray array];
    }
    if (account.pvBuyArr.count == 0) {
        account.pvBuyArr = [NSMutableArray array];
    }
    NSHomeCell * cell = (NSHomeCell *)[self collectionView:collectionView cellForItemAtIndexPath:indexPath];
    if (cell.isLocked) {
        if (collectionView == self.imageCollectionView) {
            if (account.checkPPNum > 0) {
                [account.ppBuyArr addObject:[NSString stringWithFormat:@"%ld",indexPath.row]];
                account.checkPPNum -= 1;
                [MBUserAccount saveAccount:account];
                [self.imageCollectionView reloadData];
            } else {
                self.homePPVPopView.isVideo = NO;
                self.homeFirstPopView.hidden = NO;
            }
        } else {
            if (account.checkPVNum > 0) {
                [account.pvBuyArr addObject:[NSString stringWithFormat:@"%ld",indexPath.row]];
                account.checkPVNum -= 1;
                [MBUserAccount saveAccount:account];
                [self.videoCollectionView reloadData];
            } else {
                self.homePPVPopView.isVideo = YES;
                self.homeFirstPopView.hidden = NO;
            }
        }
        
    } else {
        
        [self.dataArr removeAllObjects];
        GKPhoto *data = [GKPhoto new];
        if (collectionView == self.imageCollectionView) {
            data.image = cell.iconImageView.image;
            data.sourceImageView = cell.iconImageView;
            [self.dataArr addObject:data];
        } else {
            NSString *path = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%@.mp4",self.videoArr[indexPath.row]] ofType:nil];
            data.videoUrl = UrlWithString(self.videoArr[indexPath.row]);
            data.sourceImageView = cell.iconImageView;
            [self.dataArr addObject:data];
        }
        GKPhotoBrowser *browser = [GKPhotoBrowser photoBrowserWithPhotos:self.dataArr currentIndex:0];
        browser.showStyle = GKPhotoBrowserShowStyleZoom;
        browser.hideStyle = GKPhotoBrowserHideStyleZoomScale;
        browser.animDuration = 0.1;
        browser.hidesVideoSlider = YES;
        [browser showFromVC:self];
    }
}

#pragma mark - UI
- (void)setupUI {
    
    [self.view addSubview:self.backImageView];
    [self.backImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    [self.view addSubview:self.titleLab];
    [self.titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(StatusBarHeight+MBHeightScale(10));
        make.left.mas_equalTo(MBWidthScale(18));
    }];
    
    [self.view addSubview:self.messageBtn];
    [self.messageBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.titleLab);
        make.right.mas_equalTo(MBWidthScale(-20));
//        make.width.mas_equalTo(MBWidthScale(37));
//        make.height.mas_equalTo(MBHeightScale(26));
    }];
    
    [self.view addSubview:self.recruitmentBtn];
    [self.recruitmentBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.titleLab.mas_bottom).offset(MBHeightScale(20));
        make.left.mas_equalTo(MBWidthScale(18));
        make.width.mas_equalTo(ScreenWidth-MBWidthScale(36));
        make.height.mas_equalTo(MBHeightScale(153));
    }];
    
    [self.view addSubview:self.headerView];
    [self.headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.recruitmentBtn.mas_bottom).offset(MBHeightScale(20));
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(MBHeightScale(32));
    }];
    
    [self.view addSubview:self.imageCollectionView];
    [self.imageCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(self.titleLab.mas_bottom).offset(MBHeightScale(20));
        make.top.equalTo(self.headerView.mas_bottom).offset(MBHeightScale(20));
        make.left.mas_equalTo(MBWidthScale(18));
        make.width.mas_equalTo(ScreenWidth-MBWidthScale(36));
        make.bottom.equalTo(self.view);
    }];
    
    [self.view addSubview:self.videoCollectionView];
    [self.videoCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(self.titleLab.mas_bottom).offset(MBHeightScale(20));
        make.top.equalTo(self.headerView.mas_bottom).offset(MBHeightScale(20));
        make.left.mas_equalTo(MBWidthScale(18));
        make.width.mas_equalTo(ScreenWidth-MBWidthScale(36));
        make.bottom.equalTo(self.view);
    }];
    
    //pop
    [kKeyWindow addSubview:self.homeFirstPopView];
    [kKeyWindow addSubview:self.homePPVPopView];
    
    
    self.imageCollectionView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        if (self.imageArr.count < 18) {
            NSInteger num = 4;
            if (self.imageArr.count + 4 > 18) {
                num = 18;
            } else {
                num = self.imageArr.count + 4;
            }
            for (NSInteger i = self.imageArr.count; i < num; i++) {
                [self.imageArr addObject:[NSString stringWithFormat:@"https://storage.googleapis.com/meboo-online-b68e7.appspot.com/images4/home_cell_images_%ld.jpeg",(long)(i+1)]];
            }
        }
        [self.imageCollectionView reloadData];
        if (self.imageArr.count >= 18) {
            [self.imageCollectionView.mj_footer endRefreshingWithNoMoreData];
        } else {
            [self.imageCollectionView.mj_footer endRefreshing];
        }
    }];
    
    self.videoCollectionView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        if (self.videoAvatarArr.count < 11) {
            NSInteger num = 4;
            if (self.videoAvatarArr.count + 4 > 11) {
                num = 11;
            } else {
                num = self.videoAvatarArr.count + 4;
            }
            for (NSInteger i = self.videoAvatarArr.count; i < num; i++) {
                [self.videoAvatarArr addObject:[NSString stringWithFormat:@"https://storage.googleapis.com/meboo-online-b68e7.appspot.com/images4/home_cell_videosavatar_%ld.jpg",(long)(i+1)]];
            }
        }
        [self.videoCollectionView reloadData];
        if (self.videoAvatarArr.count >= 11) {
            [self.videoCollectionView.mj_footer endRefreshingWithNoMoreData];
        } else {
            [self.videoCollectionView.mj_footer endRefreshing];
        }
    }];
    
}

#pragma mark - Setter && Getter
- (UILabel *)titleLab {
    if (!_titleLab) {
        _titleLab = [UILabel new];
        _titleLab.text = @"Meboo";
        _titleLab.font = PDBoldScale(30);
        _titleLab.textColor = HEXS(@"B92176");
    }
    return _titleLab;
}

- (UIButton *)messageBtn {
    if (!_messageBtn) {
        _messageBtn = [[UIButton alloc] init];
        [_messageBtn setYXEnlargeEdgeWithTop:10 right:10 bottom:10 left:10];
        [_messageBtn setBackgroundImage:ImageWithName(@"common_chat") forState:0];
        [_messageBtn addTarget:self action:@selector(messageAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _messageBtn;
}

- (UIButton *)recruitmentBtn {
    if (!_recruitmentBtn) {
        _recruitmentBtn = [[UIButton alloc] init];
        [_recruitmentBtn setBackgroundColor:UIColor.clearColor];
        [_recruitmentBtn setBackgroundImage:ImageWithName(@"home_banner_0") forState:0];
        [_recruitmentBtn addTarget:self action:@selector(recruitmentAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _recruitmentBtn;
}

- (UIImageView *)backImageView {
    if (!_backImageView) {
        _backImageView = [UIImageView new];
        _backImageView.image = ImageWithName(@"home_back_image");
    }
    return _backImageView;
}

- (UICollectionView *)imageCollectionView {
    if (!_imageCollectionView) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.minimumInteritemSpacing = 0;
        flowLayout.minimumLineSpacing = 0;
        _imageCollectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:flowLayout];
        _imageCollectionView.backgroundColor = UIColor.clearColor;
        _imageCollectionView.delegate = self;
        _imageCollectionView.dataSource = self;
        _imageCollectionView.showsVerticalScrollIndicator = NO;
        _imageCollectionView.showsHorizontalScrollIndicator = NO;
        [_imageCollectionView registerClass:[NSHomeCell class] forCellWithReuseIdentifier:@"NSHomeCell"];
    }
    return _imageCollectionView;
}

- (UICollectionView *)videoCollectionView {
    if (!_videoCollectionView) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.minimumInteritemSpacing = 0;
        flowLayout.minimumLineSpacing = 0;
        _videoCollectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:flowLayout];
        _videoCollectionView.backgroundColor = UIColor.clearColor;
        _videoCollectionView.delegate = self;
        _videoCollectionView.dataSource = self;
        _videoCollectionView.hidden = YES;
        _videoCollectionView.showsVerticalScrollIndicator = NO;
        _videoCollectionView.showsHorizontalScrollIndicator = NO;
        [_videoCollectionView registerClass:[NSHomeCell class] forCellWithReuseIdentifier:@"NSHomeCell"];
    }
    return _videoCollectionView;
}

- (MBHomeListHeaderView *)headerView {
    if (!_headerView) {
        __WeakSelf
        _headerView = [MBHomeListHeaderView new];
        _headerView.switchBlock = ^(BOOL isVideo) {
            weakSelf.videoCollectionView.hidden = !isVideo;
            weakSelf.imageCollectionView.hidden = isVideo;
        };
    }
    return _headerView;
}

- (NSMutableArray *)dataArr {
    if (!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

//pop
- (MBHomeFirstPopView *)homeFirstPopView {
    if (!_homeFirstPopView) {
        __WeakSelf
        _homeFirstPopView = [[MBHomeFirstPopView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
        _homeFirstPopView.nextBlock = ^{
            weakSelf.homeFirstPopView.hidden = YES;
            weakSelf.homePPVPopView.hidden = NO;
        };
    }
    return _homeFirstPopView;
}

- (MBHomePPVPopView *)homePPVPopView {
    if (!_homePPVPopView) {
        _homePPVPopView = [[MBHomePPVPopView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
        _homePPVPopView.isVideo = YES;
    }
    return _homePPVPopView;
}

- (NSMutableArray *)imageArr {
    if (!_imageArr) {
        _imageArr = [NSMutableArray array];
        for (int i = 0; i<4; i++) {
            [_imageArr addObject:[NSString stringWithFormat:@"https://storage.googleapis.com/meboo-online-b68e7.appspot.com/images4/home_cell_images_%d.jpeg",i+1]];
        }
    }
    return _imageArr;
}

- (NSMutableArray *)videoArr {
    if (!_videoArr) {
        _videoArr = [NSMutableArray array];
        for (int i = 0; i<11; i++) {
            [_videoArr addObject:[NSString stringWithFormat:@"https://storage.googleapis.com/meboo-online-b68e7.appspot.com/images4/home_cell_videos_%d.mp4",i+1]];
        }
    }
    return _videoArr;
}

- (NSMutableArray *)videoAvatarArr {
    if (!_videoAvatarArr) {
        _videoAvatarArr = [NSMutableArray array];
        for (int i = 0; i<4; i++) {
            [_videoAvatarArr addObject:[NSString stringWithFormat:@"https://storage.googleapis.com/meboo-online-b68e7.appspot.com/images4/home_cell_videosavatar_%d.jpg",i+1]];
        }
    }
    return _videoAvatarArr;
}

- (NSMutableArray *)videoTimeArr {
    if (!_videoTimeArr) {
        _videoTimeArr = [NSMutableArray arrayWithArray:@[@"33",@"08",@"36",@"09",@"09",@"10",@"06",@"09",@"11",@"15",@"53"]];
    }
    return _videoTimeArr;
}

@end
